package com.smilive.start.netty.rpc.handle;

import com.smilive.start.netty.rpc.ServicesFactory;
import com.smilive.start.netty.rpc.message.RpcRequestMessage;
import com.smilive.start.netty.rpc.message.RpcResponseMessage;
import com.smilive.start.netty.rpc.server.RpcHelloServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

/**
 * @program: netty
 * @Date: 2022-01-11 10:11
 * @Author: smilive
 * @Description:
 */
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) {
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        rpcResponseMessage.setSequenceId(msg.getSequenceId());
        try {
            RpcHelloServer rpcHelloServer = (RpcHelloServer) ServicesFactory.getInstance(Class.forName(msg.getInterfaceName()));
            Method method = rpcHelloServer.getClass().getMethod(msg.getMethodName(), msg.getParameterTypes());
            Object invoke = method.invoke(rpcHelloServer, msg.getParameterValue());
            rpcResponseMessage.setReturnValue(invoke);
        }catch (Exception e){
            e.printStackTrace();
            rpcResponseMessage.setExceptionValue(e);
        }
        ctx.writeAndFlush(rpcResponseMessage);

    }
}
